<?php
class service_keyword{
	static public function getTop($limit=20){
		$dao = new DaoKeyword();
		$keywords = $dao->getList(" 1 order by isTop desc,num desc",$limit);
		return $keywords;
	}
	/**
	  *根据ID获取关键字，以半角逗号分割
	  *@param $ids 关键字ID，多个ID以逗号分开
	  *@return 返回获取到的name
	  */
	static public function getNameByID($ids){
		$ids = self::strToArray($ids);
		$name = '';
		if(empty($ids)) return $name; 
		foreach($ids as $id){
			$key = self::getOne($id);
			if(empty($key)||$key['name']=='') continue;
			$name .= $key['name'].',';
		}
		return rtrim(trim($name),',');
	}
	/**
	  *通过ID获取关键字信息
	  *@param $id 关键字ID
	  *@return 获取到返回关键字信息，否则返回空数组
	  */
    static private function getOne($id){
		$dao = new DaoKeyword();
		$key = $dao->getOne(" id='{$id}'");
		if(empty($key)) return array();
		return $key;
	}
	/**
	  *保存关键字
	  *@param $keyword 关键字字符串以半角逗号分割开 key1,key2,key3
	  *@return 保存成功后，把关键字对应的ID拼接成字符串返回
	  */
	static public function save($keyword){
		if($keyword=='') return '';	
		$keywords = self::strToArray($keyword);
		$dao = new DaoKeyword();
		$ids = '';
		foreach($keywords as $item){
			if(trim($item)=='') continue;
			$key = self::getOneByName(trim($item));
			if(!empty($key)){
				$dao->update(" id='".$key['id']."'",array('num'=>$key['num']+1));
				$ids .= $key['id'].',';
			}else{
				$id = $dao->insert(array('name'=>$item,'num'=>1));
				$ids .= $id.',';
			}	
		}
		return rtrim(trim($ids),',');
	}
	/**
	  *通过关键字获取关键字数组
	  *@param $name 关键字
	  *@return 如果找到返回关键字数组，否则返回空数组
	  */
	static private function getOneByName($name){
		if($name=='') return array();
		$dao = new DaoKeyword();
		$key = $dao->getOne(" name = '{$name}'");
		return $key;
	}
	/**
	  *字符串转换为数组,以半角逗号分割
	  *@param $str 需要处理的字符串
	  *@return 返回转换后的字符串
	  */
	static private function strToArray($str){
		if($str == '') return array();
		$str = trim(trim($str),',');
		return explode(',',$str);
	}
}
?>
